/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package main.java.cn.webrx;

import java.io.File;
import java.io.FileInputStream;

/**
 * <p>Project: jse2204 - CountFiles
 * <p>Powered by webrx On 2022-09-21 14:17:26
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class CountFiles {
    static int num = 0;
    static int rows = 0;

    public static void main(String[] args) {
        String dir = System.getProperty("user.dir");
        dir = "D:\\0418\\javase2022\\src";
        dir = "C:\\Users\\Administrator\\Desktop\\DemoAll\\DemoAll\\out";
        dir = "D:\\download\\jdk-19_windows-x64_bin\\jdk-19\\lib\\src";
        dir = "C:\\Users\\Administrator\\Desktop\\DemoAll\\DemoAll";
        File s = new File(dir);

        count(s);

        System.out.println("----------------------------");
        System.out.println("总共："+num+"个java文件");

        System.out.println("共" + rows + "行");
    }

    /**
     * Description: 递归遍历目录，使用静态的成员变量，统计java文件的个数
     * @date: 2022/9/21 14:37
     * @params: [java.io.File]
     * @return: void
     */
    public static void count(File src) {
        if (src.isDirectory()) {
            File[] fs = src.listFiles();
            for (File f : fs) {
                if (f.isDirectory()) count(f);
                if (f.isFile() && f.getName().endsWith(".java")){
                    ++num;
                    rows+=getFileRows(f);
                    //System.out.printf("文件：%s (%d行)。%n",f.getAbsolutePath(),getFileRows(f));
                }
            }

        }
    }

    /**
     * Description: 获取文件的行数
     * @date: 2022/9/21 14:37
     * @params: [java.io.File]
     * @return: int
     */
    public static int getFileRows(File src) {
        int rows = 0;
        try (FileInputStream fis = new FileInputStream(src)) {
            rows = (int) new String(fis.readAllBytes()).lines().count();
        } catch (Exception e) {
        }
        return rows;
    }
}
